import React from 'react';
import { Redirect, Route, RouteProps } from 'react-router-dom';
import { hasToken } from '../../utils/storage';

export type LocationStateType = {
  fromPath: string;
};

export function AuthRoute({ path, component: Component, ...restProps }: AuthRouteProps) {
  return (
    <Route
      {...restProps}
      path={path}
      render={(_props: any) => {
        if (hasToken()) {
          return <Component {..._props} />;
        }

        return (
          <Redirect
            to={{
              pathname: '/login',
              state: {
                fromPath: path,
              } as LocationStateType,
            }}
          />
        );
      }}
    />
  );
}

export interface AuthRouteProps extends RouteProps {
  component: React.FC;
}
